//
//  json-data.swift
//  Pods
//
//  Created by zhu xietong on 2017/8/8.
//
//

import Foundation
extension Data
{
    
    
    typealias object = [String:Any]
    
    
    public func json<T>(_ `default`:T) -> T {
        do {
            if let obj = try JSONSerialization.jsonObject(with: self, options: JSONSerialization.ReadingOptions.mutableContainers) as? T
            {
                return obj
            }
        } catch {
            print(error)
        }
        return `default`
    }
    
    
    public var jsonString:String{
        get{
            let str = String(data: self, encoding: .utf8)
            return str!
        }
        //        do {
        //           let str = String(data: self, encoding: .utf8)
        //
        //        } catch {
        //            print(error)
        //        }
        //        return nil
    }
    
}

extension Array{
    public var body:Data?{
        get{
            var data:Data?
            
            do {
                data = try JSONSerialization.data(withJSONObject: self, options: [])
            } catch {
                print(error)
            }
            return data
        }
        
    }
    
}

extension Dictionary{
    
    public var body:Data?{
        get{
            var data:Data?
            
            do {
                data = try JSONSerialization.data(withJSONObject: self, options: [])
            } catch {
                print(error)
            }
            return data
        }
        
    }
    
}
